package com.shoulder.authorizationserver.enhancer;

import com.shoulder.core.api.ApiUser;
import com.shoulder.core.utils.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
 * Copyright (c) 2024-2050 heguangchuan <596767880@qq.com>
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * <a href="http://www.apache.org/licenses/LICENSE-2.0">...</a>
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * <p>
 * 哎 太难了 没想到只是写着玩玩  却耐着性子一直写下来了
 * @author 596767880@qq.com
 * @since 2024/5/10 下午5:21
 */
public class DefaultJwtTokenEnhancer implements JwtTokenEnhancer {
    @Override
    public void enhance(JwtEncodingContext context) {
        JwtClaimsSet.Builder claims = context.getClaims();
        Object principal = context.getPrincipal().getPrincipal();
        if (principal instanceof UserDetails user) {
            List<String> collect = user.getAuthorities().stream().map(GrantedAuthority::getAuthority).distinct().collect(Collectors.toList());
            //   claims.claim("roles", collect);
            Set<String> authorizedScopes = context.getAuthorizedScopes();
            collect.addAll(authorizedScopes);
            ApiUser apiUser = new ApiUser();
            BeanUtils.copyProperties(user, apiUser);
            MapUtils.bean2Map(apiUser).forEach((k, v) -> {
                if (v != null) {
                    claims.claim(k, v);
                }
            });
        }
        //自定义一些东西
        claims.claim("author", "596767880@qq.com");

        if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
            // Customize headers/claims for access_token

        } else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
            // Customize headers/claims for id_token

        }
    }
}
